package com.eduhzy.ttw.teacher.mvp.presenter;

import android.app.Application;

import com.blankj.utilcode.util.ObjectUtils;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.MessageCode;
import com.eduhzy.ttw.teacher.mvp.contract.PhoneVerifyContract;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


public class PhoneVerifyPresenter extends BasePresenter<PhoneVerifyContract.Model, PhoneVerifyContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public PhoneVerifyPresenter(PhoneVerifyContract.Model model, PhoneVerifyContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getSmsCode(String phone, String scene) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("mobile", phone);
        map.put("template", scene);

        mModel.getPhoneCode(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<MessageCode>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<MessageCode> loginData) {
                        if (loginData.isResult()) {
                            if (ObjectUtils.isNotEmpty(loginData.getMessage())) {
                                RxUtil.showTipDialog(mRootView.getActivity(), QMUITipDialog.Builder.ICON_TYPE_FAIL, loginData.getMessage());
                            }
                            mRootView.setMessageCode(loginData.getData().getCode());
                        } else {
                            mRootView.showMessage(loginData.getMessage());
                            mRootView.cancelCounter();
                        }
                    }
                });
    }
}
